﻿using System.Web.Mvc;

using WikeSoft.Enterprise.Interfaces.Sys;

namespace WikeSoft.Web
{
    

    /// <summary>
    /// 密码过期过滤器
    /// </summary>
    public class PasswordExpirationAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!NeedValidate(filterContext))
                return;
            var principal = filterContext.HttpContext.User;
            var userService = DependencyResolver.Current.GetService<IUserService>();
           
            var isPasswordExpirated = userService.IsPasswordExpirated(principal.Identity.GetLoginUserId());
            if (isPasswordExpirated)
            {
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    var tips = "你的密码已过期，请修改密码";
                    filterContext.Result = new JsonResult
                    {
                        Data = new { success = false, message = tips },
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
                }
                else
                {
                    filterContext.Result = new RedirectResult("/User/ChangePassword");
                }
            }
        }

        /// <summary>
        /// 是否需要验证
        /// </summary>
        /// <param name="filterContext"></param>
        /// <returns></returns>
        private static bool NeedValidate(ActionExecutingContext filterContext)
        {
            if (filterContext.IsChildAction || filterContext.HttpContext.Request.IsAjaxRequest())
                return false;
            var anonymousType = typeof(AllowAnonymousAttribute);
            var ignoreType = typeof(IgnorePasswordExpirationAttribute);
            var actionDescriptor = filterContext.ActionDescriptor;
            var controllerDescripter = filterContext.ActionDescriptor.ControllerDescriptor;
            var ignoreValidation = actionDescriptor.IsDefined(anonymousType, true) ||
                              controllerDescripter.IsDefined(anonymousType, true) ||
                              actionDescriptor.IsDefined(ignoreType, true) ||
                              controllerDescripter.IsDefined(ignoreType, true);
            var isChild = filterContext.IsChildAction;
            var user = filterContext.HttpContext.User;
            return !ignoreValidation && !isChild && user != null;
        }
    }
}